﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Compilation;
using System.Web.SessionState;
using System.Web.UI;
using Ajax.BLL;
using Ajax.Model;

namespace Ajax.HttpHandlers
{
    /// <summary>
    /// 进行URL重写
    /// </summary>
    public class UrlRewriter : IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public UrlRewriter()
        {

        }
        /// <summary>
        /// 替换重写URL
        /// </summary>
        /// <param name="context">HttpContext对象</param>
        public void ProcessRequest(HttpContext context)
        {
            if (context == null) return;
            string RawUrl = context.Request.RawUrl;   //获取当前访问的重写过的虚假URL
            List<RegexInfo> _regex_list = RewriterCache.ReadRewriterRule(context);
            foreach (RegexInfo r in _regex_list)
            {
                //建立正则表达式
                Regex Reg = new Regex(r.NewPath, RegexOptions.IgnoreCase);
                Match m = Reg.Match(RawUrl);//匹配
                if (m.Success)//成功
                {
                    RawUrl = Reg.Replace(RawUrl, r.RealPath);//匹配出其真实的URL
                    context.Server.Execute(RawUrl);
                    context.Response.End();
                    return;
                }
            }
            IHttpHandler hander = BuildManager.CreateInstanceFromVirtualPath(RawUrl, typeof(Page)) as IHttpHandler;
            hander.ProcessRequest(context);
        }

        // 重写 IsReusable 属性. 
        public bool IsReusable
        {
            get { return true; }
        }

    }
}